<?php
//判断是否是cli脚本执行
if(!function_exists('is_cli'))
{
    /**
     * Is CLI?
     * Test to see if a request was made from the command line.
     * @return 	bool
     */
    function is_cli()
    {
        return (PHP_SAPI === 'cli' OR defined('STDIN'));
    }
}

/*
* table数据转array
*/
if(!function_exists('get_td_array'))
{
    function get_td_array($table) {
        $table = preg_replace("'<table[^>]*?>'si","",$table);
        $table = preg_replace("'<tr[^>]*?>'si","",$table);
        $table = preg_replace("'<td[^>]*?>'si","",$table);
        $table = str_replace("</tr>","{tr}",$table);
        $table = str_replace("</td>","{td}",$table);
        //去掉 HTML 标记 
        $table = preg_replace("'<[/!]*?[^<>]*?>'si","",$table);
        //去掉空白字符 
        $table = preg_replace("'([rn])[s]+'","",$table);
        $table = str_replace(" ","",$table);
        $table = str_replace(" ","",$table);
        $table = explode('{tr}', $table);
        array_pop($table);
        foreach ($table as $key=>$tr) {
            $td = explode('{td}', $tr);
            array_pop($td);
            $td_array[] = $td;
        }
        return $td_array;
    }
}

/*
* 返回表格中对应的数据
* $filePath 对应的上传表格存放路径
*/
if(!function_exists('xlsToArr'))
{
    function xlsToArr($filepath = ''){
        //接收参数
        if(!$filepath){//如果没有传递过来对应的参数路径
            return false;
        }
        
        //读取csv内容
        $handle = fopen($filepath, 'r');
        $c_handle = fopen($filepath, 'r');
        //获取第一行
        $firstLineStr = iconv('gb2312', 'utf-8', fread($c_handle, 1000));
        fclose($c_handle); //关闭指针
        //判断当前传入的xls文件内容是否为table
        if($firstLineStr){//说明是不存在html元素
            $result = [];
            $n = 0;
            while(!feof($handle)) {
                $nowLineStr = iconv('gb2312', 'utf-8', fgets($handle));
                $data = explode("\t", $nowLineStr);
                $num = count($data);

                for ($i = 0;$i < $num;$i++) {
                    $result[$n][$i] = $data[$i];
                }
                $n++;
            }
        }
        else{//存在html元素
            $result = '';
            while(!feof($handle)) {
                $result.= fgets($handle);
            }
            
            $result = get_td_array($result);
        }
        P($result);
        fclose($handle); //关闭指针
        unset($result[0]);
        
        return array_values($result);
    }
}

/*
* 返回xls文件所需要的数据
* $titles 头部字段数组
* $data 内容字段数组
*/
if(!function_exists('makeXls'))
{
    function makeXls($titles = [], $data = []){
        @error_reporting(E_ERROR | E_PARSE);
        $str = '';
        
        //输出头信息
        $str.= '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta http-equiv="expires" content="Mon, 06 Jan 1999 00:00:01 GMT"><meta http-equiv=Content-Type content="text/html; charset=utf-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name></x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head>';
        $str.= '<table>';
        //拼接第一行字段信息
        $str.= '<tr>';
        if(!empty($titles) && is_array($titles)){
            foreach ($titles as $v) {
                $str.= '<th>'.$v.'</th>';
            }
        }
        $str.= '</tr>';
        unset($titles);
        if(!empty($data) && is_array($data)){
            foreach($data as $k => $v){
                $str.= '<tr>';
                if(!empty($v) && is_array($v)){
                    foreach ($v as $item) {
                        $str.= '<td style="vnd.ms-excel.numberformat:@">'.$item.'</td>';
                    }
                }
                $str.= '</tr>';
            }
            unset($data[$k]);
        }
        
        $str.= '</table>';
        
        return $str;
    }
}

/*
* 导出xls文件代码片段
* $filename 输出的文件名称
* $titles 头部字段数组
* $data 内容字段数组
*/
if(!function_exists('exportXls'))
{
    function exportXls($filename, $titles = [], $data = []){
        @error_reporting(E_ERROR | E_PARSE); 
        header("Content-Type: application/vnd.ms-excel");
        header("Accept-Ranges:bytes");
        header("Content-Disposition:attachment;filename={$filename}.xls");
        header("Pragma: no-cache");
        header("Expires: 0");
        //输出头信息
        echo '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta http-equiv="expires" content="Mon, 06 Jan 1999 00:00:01 GMT"><meta http-equiv=Content-Type content="text/html; charset=utf-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name></x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head>';
        echo '<table>';
        //拼接第一行字段信息
        echo '<tr>';
        if(!empty($titles) && is_array($titles)){
            foreach ($titles as $v) {
                echo '<th>'.$v.'</th>';
            }
        }
        echo '</tr>';
        unset($titles);
        if(!empty($data) && is_array($data)){
            foreach($data as $k => $v){
                echo '<tr>';
                if(!empty($v) && is_array($v)){
                    foreach ($v as $item) {
                        echo '<td style="vnd.ms-excel.numberformat:@">'.$item.'</td>';
                    }
                }
                echo '</tr>';
            }
            unset($data[$k]);
        }
        
        echo '</table>';
    }
}

//写配置文件
function wconfig($file, $arr){
    file_put_contents(SITE_ROOT."/data/file/{$file}", serialize($arr));
}
//读配置文件
function rconfig($file, $key=''){
    $content = @file_get_contents(SITE_ROOT."/data/file/{$file}");

    $config = unserialize($content);
    if(!$key){
        return $config;
    }
    else{
        return $config[$key];
    }
}
//写INI文件
function write_ini_file($assoc_arr, $path, $has_sections=FALSE) { 
    $content = ""; 
    if ($has_sections) { 
        foreach ($assoc_arr as $key=>$elem) { 
            $content .= "[".$key."]\n"; 
           
            foreach ($elem as $key2=>$elem2) { 
                if(is_array($elem2)){ 
                    for($i=0;$i<count($elem2);$i++) 
                    { 
                        $content .= $key2."[] = '".$elem2[$i]."'\n"; 
                    } 
                }else if($elem2==""){
                	$content .= $key2." = \n";
                }else{
                	$content .= $key2." = '".$elem2."'\n";
                } 
            } 
        }
        file_put_contents(SITE_ROOT."/data/file/ip_conf.ini", $content);       
    }        
}
//读INI文件
function readini($name){
	//echo (SITE_ROOT.'data/file/'.$name);die;
	if (file_exists(SITE_ROOT.'data/file/'.$name)){
		$data = parse_ini_file(SITE_ROOT.'data/file/'.$name,true);
		if ($data){
			return $data;
		}
	}else {
		return false;
	}
}
function gpc($name,$w = 'GPC',$default = ''){
	$i = 0;
	$w = strtoupper($w);
	for($i = 0; $i < strlen($w); $i++) {
		if($w[$i] == 'G' && isset($_GET[$name])) return $_GET[$name];
		if($w[$i] == 'P' && isset($_POST[$name])) return $_POST[$name];
		if($w[$i] == 'C' && isset($_COOKIE[$name])) return $_COOKIE[$name];
	}
	return $default;
}

/**
 * 密码加密函数
 *
 * @param string $password
 * @return string $encode_password
 * @author HumingXu E-mail:huming17@126.com
 */
function encode_password($password){
    $encode_password = '';
    $encode_password = sha1( md5( $password ) );
    return $encode_password;
}

/**
 * 获取分类名称函数
 *
 * @param int $info_cateid
 * @return string $cate_title
 * @author HumingXu E-mail:huming17@126.com
 */
function get_title_by_info_cateid($info_cateid){
    $cate_title = '';
    if(!empty($info_cateid)){
        $cate_title_sql = "SELECT title FROM ".DB::table('content_cate')." WHERE info_cateid='".$info_cateid."' LIMIT 1";
        $cate_title = DB::result_first($cate_title_sql);
    }
    return $cate_title;
}

/**
 * 新增token信息到token表
 */
function insertToken($token = '', $user_id = ''){
    //不被清除掉的token对应id
    $s_commonTkId = 154;
    $a_commonTkId = 178;
    //如果任意一个参数无效即无效
    if(!$token || ! $user_id){
        return false;
    }
    $time = time();
    // 1.新增token
    $insert_data['token'] = $token;
    $insert_data['user_id'] = $user_id;
    $insert_data['ctime'] = $time;
    $insert_data['mtime'] = $time;
    $tk_id = DB::insert('token', $insert_data, true);
    // 2.将原有用户id对应的token置为无效
    if($tk_id){
        if($user_id == 24){//如果用户是24号的话不清除万能token
            DB::update('token', ['is_valid' => 0, 'mtime' => $time], ' user_id = '.$user_id.' and tk_id <> '.$tk_id.' and tk_id <> '.$s_commonTkId);
        }
        elseif($user_id == 88){//如果用户是88号的话不清除万能token
            DB::update('token', ['is_valid' => 0, 'mtime' => $time], ' user_id = '.$user_id.' and tk_id <> '.$tk_id.' and tk_id <> '.$a_commonTkId);
        }
        else{
            DB::update('token', ['is_valid' => 0, 'mtime' => $time], ' user_id = '.$user_id.' and tk_id <> '.$tk_id);
        }
    }
    
    return true;
}

/**
 * 新增登录信息到pre_user_login_log表
 */
function insertLoginLog($token = '', $user_id = '', $type = 0){
    if(!$token || !$user_id){
        return false;
    }
    
    // 1.新增token
    $insert_data['ull_token'] = $token;
    $insert_data['ull_user_id'] = $user_id;
    $insert_data['ull_type'] = $type;
    $insert_data['ctime'] = time();
    $ull_id = DB::insert('user_login_log', $insert_data, true);
    
    if($ull_id){
        return true;
    }
    
    return false;
}

/**
 * 更新token信息
 */
function updateToken($token = ''){
    if(!$token){
        return false;
    }
    
    DB::update('token', ['mtime' => time()], ['token' => $token, 'is_valid' => 1]);
    return true;
}

/**
 * 检测token是否有效
 */
function checkToken($token = ''){
    if(!$token){
        return false;
    }

    $sql = "select count(*) as cnt from ".DB::table('token')." where is_valid = 1 and token = '".$token."' LIMIT 1";
    $cnt = DB::result_first($sql);
    
    if($cnt > 0){//如果有说明存在，此处进行时效性判断
        $time = time();
        
        $sql_mtime = "select mtime from ".DB::table('token')." where is_valid = 1 and token = '".$token."' LIMIT 1";
        $mtime = DB::result_first($sql_mtime);
        
        //生存时间为30分钟 30 * 60 = 1800
        $liveTime = $mtime + 1800;
        if($liveTime < $time){//最大生存时间小余当前时间 用户长久不动  失效了
            return false;
        }
        
        return true;
    }
    
    return false;
}

/**
 * 页面跳转函数
 *
 * @param int $info_cateid
 * @return string $cate_title
 * @author HumingXu E-mail:huming17@126.com
 */
function zshowmessage($message, $url_forward = '', $values = array(), $extraparam = array(), $custom = 0) {
	@header("location: ".$url_forward);
}

//DEBUG 获取模版列表数组
function get_templates(){
    $tpldir_array = array();
    $tpldir_path = SITE_ROOT.'template';
    $tpldir_array = directoryToArray($tpldir_path, false,  true, false);
    foreach($tpldir_array AS $key => $value){
        $tpldir_array[$key] = str_ireplace($tpldir_path,'',$value);
        $tpldir_array[$key] = str_ireplace(array('\\','/'),'',$tpldir_array[$key]);
    }
    return $tpldir_array;
}

/*
 * HTML 中返回第一个图片
 * get_first_imgpath_from_html
 * @pram string $html 
 * @return string img src
 * @author xuhm
 */

function get_first_imgpath_from_html($html){
    $matches = array();
    preg_match_all("/<img(.*)(src=\"[^\"]+\")[^>]+>/isU", $html, $matches);
    return $matches[2][0];
}

/*
 * 后台信息分类数据数组树格式化函数
 * @pram 一维 array $array
 * @return 一维 $array tree
 */
function dbarr2tree($tree, $rootId = 0) {
    $return = array();
    foreach($tree as $leaf) {
        if($leaf['info_catepid'] == $rootId) {
            foreach($tree as $subleaf) {
                if($subleaf['info_catepid'] == $leaf['info_cateid']) {
                    $leaf['children'] = dbarr2tree($tree, $leaf['info_cateid']);
                    break;
                }
            }
            $return[] = $leaf;
        }
    }
    return $return;
}

/*
 * 后台分类列表选择树HTML格式化UL格式函数
 * @pram array $array tree
 * @return html ul
 */
function tree2htmlul($tree,$relate) {
    if($relate==1){
        $bringback_id = 'relate_info_cateid';
        $bringback_title = 'title2';
    }else{
        $bringback_id = 'info_cateid';
        $bringback_title = 'title';
    }
    $tree2htmlul .= '<ul>';
    foreach($tree as $leaf) {
        $tree2htmlul .= "<li><a href='javascript:' onclick=\"$.bringBack({".$bringback_id.":'".$leaf['info_cateid']."', ".$bringback_title.":'".$leaf['title']."'})\">" .$leaf['title']."</a>";
        if(!empty($leaf['children'])) {
            $tree2htmlul .= tree2htmlul($leaf['children'],$relate);
        }
        $tree2htmlul .= '</li>';
    }
    $tree2htmlul .= '</ul>';
    return $tree2htmlul;
}

/*
 * 后台分类列表选择树HTML格式化UL格式函数 用户信息分类检索
 * @pram array $array tree
 * @return html ul
 */
function tree2htmlul_infosearch($tree,$tree_class) {
    $tree2htmlul .= '<ul class="'.$tree_class.'">';
    foreach($tree as $leaf) {
        $tree2htmlul .= "<li><a href='admin.php?mod=info&action=index&do=info_ajax&info_cateid=".$leaf['info_cateid']."' target='ajax' rel='jbsxBox'>" .$leaf['title']."</a>";
        if(!empty($leaf['children'])) {
            $tree2htmlul .= tree2htmlul_infosearch($leaf['children']);
        }
        $tree2htmlul .= '</li>';
    }
    $tree2htmlul .= '</ul>';
    return $tree2htmlul;
}

/*
 * 后台分类列表选择树HTML格式化UL格式函数 用户信息分类检索
 * @pram array $array tree
 * @return html ul
 */
function tree2htmlul_catesearch($tree,$tree_class) {
    $tree2htmlul .= '<ul class="'.$tree_class.'">';
    foreach($tree as $leaf) {
        $tree2htmlul .= "<li><a href='admin.php?mod=info_cate&action=index&do=cate_ajax&info_cateid=".$leaf['info_cateid']."' target='ajax' rel='jbsxBox'>" .$leaf['title']."</a>";
        if(!empty($leaf['children'])) {
            $tree2htmlul .= tree2htmlul_infosearch($leaf['children']);
        }
        $tree2htmlul .= '</li>';
    }
    $tree2htmlul .= '</ul>';
    return $tree2htmlul;
}

//判断奇数，是返回TRUE，否返回FALSE
 function is_odd($num){
     return (is_numeric($num)&($num&1));
 }
 //判断偶数，是返回TRUE，否返回FALSE
 function is_even($num){
     return (is_numeric($num)&(!($num&1)));
 }

 /**
 * 判断当前系统是否类linux
 * @author xuhm
 * @return int 
 *  ex: 1 = 是类linux
 *      2 = 非类linux
 *      3 = 未知系统
 */
function is_unix(){
	$return_int =3;
	$os_str=php_uname();
	if(strpos($os_str,'Ubuntu')){
		$return_int = 1;
	}elseif(strpos($os_str,'inux')){
		$return_int = 1;
	}else{
		$return_int = 2;
	}
	return $return_int;
}

/**
 * 检查升级包是否有效
 * @author xuhm
 * @return array 
 *  ex: array(
 *          'status' => '1 成功 2 失败或无效',
 *          'data_cache_pku' => '' //更新包解压目录,
 *          'patch' => array() // 更新包XML信息 
 *      )
 */
function check_pku($update_package_path){
    $return_array = array(
        'status' => '2',
        'data_cache_pku' => '',
        'patch' => array()
    );
    //DEBUG 安装包缓存目录
    $data_cache_pku = SITE_ROOT.'./data/cache/pku_'.random(4);
    if(!empty($update_package_path) && file_exists($update_package_path)){
        if(is_dir($data_cache_pku)){
            $data_cache_pku = SITE_ROOT.'./data/cache/pku_'.random(8);
        }
        dmkdir($data_cache_pku);
        //DEBUG 执行解压
        if($data_cache_pku){
            //执行PHP ZipArchive 解压
            $zip = new ZipArchive;
            if ($zip->open($update_package_path) === true) { 
                $zip->extractTo($data_cache_pku); 
                $zip->close(); 
            }
            //解析更新包XML
            //DEBUG 1.获取XML版本信息 以及升级环境要求
            $upgrade_xml = realpath($data_cache_pku.'/upgrade.xml');
            $upgrade_upgradelist = realpath($data_cache_pku.'/patch_upgradelist.txt');
            //DEBUG 2.检查版本是否匹配
            if(file_exists($upgrade_xml) && file_exists($upgrade_upgradelist)){
                $upgrade_xml_content=file_get_contents($upgrade_xml);
                $zip_upgradelist_content=file_get_contents($upgrade_upgradelist);
                //DEBUG 3.获取文件列表 检测文件
                if(!empty($upgrade_xml_content) && !empty($zip_upgradelist_content)){
                    $upgrade_xml_array = xml2array($upgrade_xml_content);
                    //DEBUG 4.检测版本是否符合和升级包对应 检测 $project_id 和 $latestversion 和 $latestrelease 是当前系统是否比配 暂未加限制 以免混淆
                    
                    //DEBUG 5.检查更新文件是否完整(检测文件列表文件MD5是否有效 由于二进制 和 ASCII网络传输后,同样文件产生的MD5不一致,因此上传方式MD5检测机制暂未添加)
                    
                    //DEBUG 6.返回更新包信息
                    if(!empty($upgrade_xml_array['patch']['latestversion']) && !empty($upgrade_xml_array['patch']['latestrelease'])){
                        $return_array['status'] = 1;
                        $return_array['data_cache_pku'] = $data_cache_pku;
                        $return_array['patch'] = $upgrade_xml_array['patch'];
                    }
                }
            }
        }
    }
    return $return_array;
}

/**
 * 获取URL上的ID参数
 * @author xuhm
 * @return string ajax_url_href 
 */

function set_ajax_url_href($url = ''){
    //DEBUG 处理 index.php?mod=index&action=info&do=detail&id=7
    //DEBUG 处理 index.php?mod=index&action=cate&do=list&id=125
    $return_ajax_url_href = '';
    $url_array = explode('=',$url);
    $url_array_num = count($url_array);
    if($url_array[($url_array_num-2)] == 'detail&id'){
        $return_ajax_url_href = "javascript:info_detail('".$url_array[($url_array_num-1)]."')";
    }elseif($url_array[($url_array_num-2)] == 'list&id'){
        $return_ajax_url_href = "javascript:waterfall('ajax','".$url_array[($url_array_num-1)]."','',1);";
    }else{
        $return_ajax_url_href = $url;
    }
    return $return_ajax_url_href;
}

/*
 * 缓存用户权限菜单数据数组树格式化函数
 * @pram 一维 array $array
 * @return 一维 $array tree
 */
function menuarr2tree($tree, $rootId = 0) {
    $return = array();
    foreach($tree as $leaf) {
        if($leaf['menu_pid'] == $rootId) {
            foreach($tree as $subleaf) {
                if($subleaf['menu_pid'] == $leaf['menu_id']) {
                    $leaf['submenu'] = menuarr2tree($tree, $leaf['menu_id']);
                    break;
                }
            }
            $return[$leaf['menu_id']] = $leaf;
        }
    }
    return $return;
}

function writetojscache() {
    $dir = DZF_ROOT . 'static/js/';
    $dh = opendir($dir);
    $remove = array(
        array(
            '/(^|\r|\n)\/\*.+?\*\/(\r|\n)/is',
            "/([^\\\:]{1})\/\/.+?(\r|\n)/",
            '/\/\/note.+?(\r|\n)/i',
            '/\/\/debug.+?(\r|\n)/i',
            '/(^|\r|\n)(\s|\t)+/',
            '/(\r|\n)/',
        ), array(
            '',
            '\1',
            '',
            '',
            '',
            '',
    ));
    while (($entry = readdir($dh)) !== false) {
        if (fileext($entry) == 'js') {
            $jsfile = $dir . $entry;
            $fp = fopen($jsfile, 'r');
            $jsdata = @fread($fp, filesize($jsfile));
            fclose($fp);
            $jsdata = preg_replace($remove[0], $remove[1], $jsdata);
            if (@$fp = fopen(DZF_ROOT . './data/cache/' . $entry, 'w')) {
                fwrite($fp, $jsdata);
                fclose($fp);
            } else {
                exit('Can not write to cache files, please check directory ./data/ and ./data/cache/ .');
            }
        }
    }
}

/*
* 函数说明 URL登录功能函数
* @author xuhm
* @pram username 用户名
* @password 用户名密码 md5(32位)后的密文
* @return 无
*/
function url_login(){
	//DEBUG 模拟登录
	$user_name = isset($_GET['user_name']) ? $_GET['user_name']:'';
	$user_password = isset($_GET['user_password']) ? $_GET['user_password']:'';
	$url = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
	$replace_pram = 'user_name='.$user_name.'&user_password='.$user_password;
	$location_url = str_replace($replace_pram,'',$url);
	if(!empty($user_name) && !empty($user_password)){
		/*
		* url pram add user_name=teacher1&user_password=e10adc3949ba59abbe56e057f20f883e
		* eg: home.php?user_name=teacher1&user_password=e10adc3949ba59abbe56e057f20f883e
		*/
		$member = DB::fetch_first("SELECT user_id,user_password from ".DB::table('user')." WHERE user_name='".$user_name."' LIMIT 1");
		if(empty($member)){
			$member = DB::fetch_first("SELECT user_id,user_password from ".DB::table('user')." WHERE user_id='".$user_name."' LIMIT 1");
		}
		if($member['user_password'] && $member['user_id']){
			$user_id=$member['user_id'];
			//校验密码 是否正确
			$uc_password = sha1($user_password);
			if($uc_password==$member['user_password']){
				//loaducenter();
				//$ucsynlogin = uc_user_synlogin($uid);
				$user['user_id']=$user_id;
				ext::synlogin($user,$user);
				header('location:'.$location_url.'');
				die;	
			}
		}
	}
}

/*
* 格式化打印
*/
function P($obj){
    echo '<pre>';
    var_dump($obj);
    echo '</pre>';
}

/*
* 函数说明 ajax 通用返回函数
* @author xuhm
* @pram $data array
* @return string
*/
function format_data($data, $api='json', $mod='', $action='', $do='',$client='wap',$lang_name='msg',$lang_key=''){
    global $_G;
    $format_return = array();
    $format_return['code']=$data['code'];
    if($data['code']!=''){
        if(empty($lang_key)){
            $format_return['msg']=lang($lang_name,$mod.'_'.$action.'_'.$do.'_'.$data['code']);
        }else{
            $format_return['msg']=lang($lang_name,$lang_key.'_'.$data['code']);
        }
    }else{
        $format_return['msg']=$data['code'];
    }
    if(empty($data['data'])){
       $format_return['data']=array();
    }else{
        $format_return['data']=$data['data'];
    }
	switch($api){
		case "json":
			$return = json_ext($format_return);
			break;
		
		case "xml":
			//@header("Content-type: application/xml");//头部输出
			$return = array2xml($format_return);
			//DEBUG XML 解析
			//$return_array = xml2array($return);
			//TODO 方法二 反向解析XML为数组 此方法位置DOM报错
			//$return = arrayxml::createXML('root', $data);
			//$result = arrayxml::xml2array($result,0);
			break;
	}
        if($_G['config']['debug_log']){
            @file_put_contents(SITE_ROOT.'./data/debug/input_log_'.date('Ymd').'.txt','RETURN : '.date('Y-m-d H:i:s').' '.$return.PHP_EOL,FILE_APPEND);
        }
	return $return;
}

/*
* 函数说明 根据树形节点的 menu_id 获取该节点路径
* @author xuhm
* @pram $data array
* @return Array(
        [0] => Array(
                [menu_id] => 1021
                [menu_pid] => 1002
                    ......
                [submenu] => Array(
                        [1025] => Array(
                                [menu_id] => 1025
                                [menu_pid] => 1021
                                ......
                            )
                        [1026] => Array(
                                [menu_id] => 1026
                                [menu_pid] => 1021
                                ......
                            )
                        [1027] => Array(
                                [menu_id] => 1027
                                [menu_pid] => 1021
                                ......
                            )
                    )
            )
    )
*/
function get_treepath($tree, $level = 0, $current_menu_id,$treepath=array('stop'=>0)) {
    foreach($tree as $leaf) {
        if($treepath['stop']==1){
            return $treepath;
            break;
        }
        if(empty($treepath['stop'])){
            if($current_menu_id == $leaf['menu_id']){
                if(0==$leaf['menu_pid']){
                    break;
                }else{
                    $treepath[$level]=$leaf;
                    $treepath = get_treepath($tree, $level + 1, $leaf['menu_pid'], $treepath);
                }
            }
        }
    }
    return $treepath;
}

/*
 * 缓存用户权限菜单数据数组树格式化函数
 * @pram 一维 array $array
 * @return 一维 $array tree
 */
function menuarr2tree2($tree, $rootId = 0) {
    $return = array();
    foreach($tree as $leaf) {
        if($leaf['menu_pid'] == $rootId) {
            foreach($tree as $subleaf) {
                if($subleaf['menu_pid'] == $leaf['menu_id']) {
                    $leaf['submenu'] = menuarr2tree($tree, $leaf['menu_id']);
                    break;
                }
            }
            $return[$leaf['menu_id']] = $leaf;
        }
    }
    return $return;
}

function dzf_curl_post($curl_post,$url){
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_NOBODY, true);
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post);
		$return_str = curl_exec($curl);
		curl_close($curl);
		return $return_str;
}

function dzf_xml_to_array($xml){
	$reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
	if(preg_match_all($reg, $xml, $matches)){
		$count = count($matches[0]);
		for($i = 0; $i < $count; $i++){
		$subxml= $matches[2][$i];
		$key = $matches[1][$i];
			if(preg_match( $reg, $subxml )){
				$arr[$key] = dzf_xml_to_array( $subxml );
			}else{
				$arr[$key] = $subxml;
			}
		}
	}
	return $arr;
}

/*
 * 加载任意业务模块方法
*/
function auto_mad($mod,$action,$do,$data=array(),$direct='',$inclass=''){
    //加载模块主对象
    $action_class_path = libfile($mod.'/'.$action, 'class','..');
    if(file_exists($action_class_path)){
        require_once $action_class_path;
        //$action_class_name = $mod.'_'.$action;
        //$action_class = new $action_class_name();
    }
    //加载模块业务对象
    require_once libfile($mod.'/'.$action, 'module','..');
    $mod_action_class = 'ctrl_'.$mod.'_'.$action;
    if($mod && $action && $do && class_exists($mod_action_class)){
        $mod_action = new $mod_action_class();
        if($inclass){
            $ctrl_name=$do;
        }else{
            $ctrl_name='do_'.$do; 
        }
        if($direct){
            $result = $mod_action->$ctrl_name($data);
        }else{
            $result = $mod_action->$ctrl_name($mod,$action,$do,$data);   
        }
    }else{
        $result = '';
    }
    return $result;
}

function mst_trade_status($mst_trade_status='') {
    $mst_trade_status_array = array(
        'WAIT_BUYER_PAY'=>'等待付款',
        'TRADE_SUCCESS'=>'支付完成',
        'TRADE_FINISHED'=>'支付结束',
        'TRADE_CLOSED'=>'支付关闭',
        'TRADE_PART_SUCCESS'=>'订单部分付款',
        'REFUND_SUCCESS'=>'退款成功',
        'REFUND_CLOSED'=>'退款关闭',
    );
    if($mst_trade_status){
        return $mst_trade_status_array[$mst_trade_status];
    }else{
        return $mst_trade_status_array;
    }
}

function mst_trade_status_all($mst_trade_status_all='') {
    $mst_trade_status_all_array = array(
        '1'=>'未付款',
        '2'=>'已付款',
        '3'=>'已成功',
        '4'=>'待评价',
        '5'=>'退款中',
        '6'=>'已评价',
        '7'=>'已关闭'
    );
    if($mst_trade_status_all){
        return $mst_trade_status_all_array[$mst_trade_status_all];
    }else{
        return $mst_trade_status_all_array;
    }
}

function moe_status($moe_status='') {
    $moe_status_array = array(
        '1'=>'待发货',
        '2'=>'待收货',
        '3'=>'已签收',
        '4'=>'已配送'
    );
    if($moe_status){
        return $moe_status_array[$moe_status];
    }else{
        return $moe_status_array;
    }
}
function trade_way($trade_way='') {
        $trade_way_array = array(
            '1'=>'支付宝',
            '2'=>'人工收款',
            '3'=>'银联支付',
            '4'=>'线下汇款',
            '5'=>'微信支付'
        );
        if($trade_way){
            return $trade_way_array[$trade_way];
        }else{
            return $trade_way_array;
        }
}
/*
*  日志记录input
*/

function debug_log(){
    @file_put_contents(SITE_ROOT.'./data/debug/input_log_'.date('Ymd').'.txt','RECEIVE: '.date('Y-m-d H:i:s').' '.json_encode($_REQUEST).PHP_EOL,FILE_APPEND);
    $php_input=file_get_contents("php://input");
    @file_put_contents(SITE_ROOT.'./data/debug/input_log_'.date('Ymd').'.txt','RECEIVE input: '.date('Y-m-d H:i:s').' '.$php_input.PHP_EOL,FILE_APPEND);
}
?>